﻿#pragma once
#include"RBTree.h"


namespace lcy
{
	template<class K, class V>
	class map
	{
		struct  MapKeyOfT
		{
			const K& operator()(const pair<K, V>& kv)
			{
				return kv.first;
			}
		};
	public:
		//pair.first 加const 不允许修改， pair.second 可以修改
		typedef typename RBTree<K, pair<const K, V>, MapKeyOfT>::iterator iterator;
		iterator begin()
		{
			return _t.begin();
		}

		iterator end()
		{
			return _t.end();
		}

		V& operator[](const K& key)
		{
			pair<iterator,bool> ret = _t.Insert(make_pair(key, V()));
			return ret.first->second;
		}

		pair<iterator,bool> insert(const pair<K, V>& kv)
		{
			return  _t.Insert(kv);
		}
	private:
		RBTree<K, pair<const K, V>, MapKeyOfT> _t;
	};

	void test_map1()
	{
		map<int, int> m;
		m.insert(make_pair(1, 1));
		m.insert(make_pair(2, 2));
		m.insert(make_pair(3, 3));
		m.insert(make_pair(4, 4));
		m.insert(make_pair(5, 5));

		map<int, int>::iterator it = m.begin();
		while(it != m.end())
		{
			cout << it->first << ":" << it->second << endl;
			++it;
		}

		for (auto e : m)
		{
			cout << e.first << ":" << e.second << endl;
		}
	}

	void test_map2()
	{
		map<string, string> dict;
		dict.insert(make_pair("sort", "排序"));
		dict.insert(make_pair("string","字符串"));
		dict.insert(make_pair("count", "计数"));
		dict.insert(make_pair("string", "~")); 

		map<string, string>::iterator it = dict.begin();
		while (it != dict.end())
		{
			cout << it->first << ":" << it->second << endl;
			//it->first = "1111";//first 为const 不允许修改
			it->second = "111";

			++it;
		}
		cout << endl;

		for (auto& kv : dict)
		{
			cout << kv.first << ":" << kv.second << endl;
		}
		cout << endl;
	}

	void test_map3()
	{
		string arr[] = {"苹果" ,"梨" ,"梨" ,"梨" ,"苹果" };
		map<string, int> countMap;
		for (auto& e : arr)
		{
			countMap[e]++;
		}

		for (auto& kv : countMap)
		{
			cout << kv.first << ":" << kv.second << endl;
		}
	}
}